import uuid

from django.core.paginator import Paginator
from django.shortcuts import render

# Create your views here.
import os
import random
import re
import string

from django.contrib.auth.hashers import check_password, make_password
from django.core.files.uploadedfile import InMemoryUploadedFile
from rest_framework import status, permissions
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.views import APIView
from django.core.cache import cache

from jiuyun import settings
from utils.decorator_ import PermissionCheck
from .models import Staff

# Create your views here.
from .serializer import StaffSerialzier


@api_view(['post'])
@permission_classes([permissions.AllowAny])
def regist(request):
    name = request.data.get('name')
    phone = request.data.get('phone','')
    address = request.data.get('address','')
    role_id = request.data.get('role','d9a0d1f9349f411ea89587905c4e8360')
    sex = request.data.get('sex', '男')
    if Staff.objects.all():
        ret = str(Staff.objects.count() + 1)
        snum = 'S' + ret.rjust(9, '0')
    else:
        snum = 'S' + '1'.rjust(9, '0')
    staff_rt = Staff.objects.filter(name=name)
    if staff_rt.exists():
        return Response({'msg': '用户名已存在'})
    u = Staff.objects.create(staff_id=uuid.uuid4().hex,
                             name=name,
                             num=snum,
                             role_id=role_id,
                             password=123456,
                             sex=sex,
                             address=address,
                             phone=phone)
    # 注册后即为登录状态
    token = Token.objects.create(user_id=u.staff_id)
    return Response({
        'msg': '注册成功',
        'token': str(token),
        'name': name
    })


@api_view(['post'])
@permission_classes([permissions.AllowAny])
def login(request):
    if not all((
            'name' in request.data,
            'password' in request.data
    )):
        return Response({'msg': 'name或password属性不存在或为空！'}, status=status.HTTP_200_OK)
    staff_rt = Staff.objects.filter(name=request.data['name'])
    if staff_rt.exists():
        user = staff_rt.first()
        if request.data['password'] != user.password:
            return Response({'msg': '用户名或口令错误'}, status=status.HTTP_200_OK)
        qs = Token.objects.filter(user=user)
        if qs.exists():
            token = qs.first()
        else:
            token = Token.objects.create(user=user)
        return Response({
            'msg': '登录成功',
            'token': str(token),
            'name': user.name,
            'phone': user.phone,
            'head': user.head,
            'sex': user.sex,
            'address': user.address,
        })
    else:
        return Response({'msg': '用户不存在，请先注册'})


@api_view(['post'])
def upload_head(request):
    staff = request.user
    head: InMemoryUploadedFile = request.FILES.get('head')
    ext = head.name.split('.')[-1]
    filename = f'{staff.staff_id}.{ext}'
    path = os.path.join(settings.HEAD_DIR, filename)
    with open(path, 'wb') as f:
        for chunk in head.chunks():
            f.write(chunk)

    head_url = settings.MEDIA_URL + 'head/' + filename
    staff.head = head_url
    staff.save()

    return Response({'path': staff.head, 'msg': '头像上传成功'})


@api_view(['put'])
def change_password(request):
    pwd = request.data.get('password')
    staff = Staff.objects.get(pk=request.user.pk)
    staff.password = pwd
    staff.save()
    return Response({'msg':'修改成功'})


@api_view(['get'])
def logout(request):
    qs = Token.objects.filter(user_id=request.user.staff_id)
    if qs.exists():
        qs.delete()
        return Response({
            'msg': '用户退出成功'
        })
    else:
        return Response({
            'msg': '用户未登录'
        })

@api_view(['get'])
def all_user(request):
    page = int(request.GET.get('page', '1'))
    size = int(request.GET.get('size', '20'))
    if request.user:
        data = Staff.objects.all()
        paginator = Paginator(data, size)
        pager = paginator.page(page)
        # 模型实例化
        approve = StaffSerialzier(pager.object_list, many=True)
        return Response({
            'data': approve.data,
            'total': paginator.count,
            'page': pager.number,  # page当前页号
            'pageSize': size,
            'pages': paginator.num_pages  # 总页数
        })
    data = StaffSerialzier(Staff.objects.all(),many=True)
    return Response({'msg':data.data})